import 'package:flutter/material.dart';

class FutureDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('异步界面的例子'),
      ),
      body: Column(
        children: <Widget>[
          //
          Expanded(
            child: Center(
              child: FutureBuilder(
                future: _mockNetworkData(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (snapshot.hasError) {
                      // 请求失败，显示错误
                      return Text("Error: ${snapshot.error}");
                    } else {
                      // 请求成功，显示数据
                      return Text("Contents: ${snapshot.data}");
                    }
                  } else {
                    // 请求未结束，显示loading
                    return CircularProgressIndicator();
                  }
                },
              ),
            ),
          ),

          //
          Expanded(
            child: Center(
              child: StreamBuilder(
                stream: _counter(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.hasError) {
                    return Text('Error: ${snapshot.error}');
                  } else {
                    switch (snapshot.connectionState) {
                      case ConnectionState.none:
                        return Text('没有Stream');
                      case ConnectionState.waiting:
                        return Text('等待数据...');
                      case ConnectionState.active:
                        return Text('active: ${snapshot.data}');
                      case ConnectionState.done:
                        return Text('Stream已关闭');
                    }
                  }
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<String> _mockNetworkData() async {
    return Future.delayed(Duration(seconds: 2), () => "我是从互联网上获取的数据");
  }

  Stream<int> _counter() {
    return Stream.periodic(Duration(seconds: 1), (i) {
      return i;
    });
  }
}